package org.jeecg.modules.hotel.exchangebed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.hotel.arrangement.service.ILwgyHotelArrangementService;
import org.jeecg.modules.hotel.exchangebed.entity.Exchange;
import org.jeecg.modules.hotel.exchangebed.mapper.ExchangeMapper;
import org.jeecg.modules.hotel.exchangebed.service.IExchangeService;
import org.jeecg.modules.hotel.history.entity.LwgyHotelHistory;
import org.jeecg.modules.hotel.history.service.ILwgyHotelHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 床位交换
 * @Author: jeecg-boot
 * @Date:   2021-02-24
 * @Version: V1.0
 */
@Service
public class ExchangeServiceImpl extends ServiceImpl<ExchangeMapper, Exchange> implements IExchangeService{
    @Resource
    private ExchangeMapper exchangeMapper;
    @Autowired
    private ILwgyHotelArrangementService lwgyHotelArrangementService;

    @Autowired
    private ILwgyHotelHistoryService lwgyHotelHistoryService;

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;

    @Override
    public   IPage<Exchange> findList(Exchange exchange) {
        IPage<Exchange> RepeatPage = new Page<>();
        List<Exchange>  queryList = new ArrayList<Exchange>();
       /* List<Exchange> list = exchangeMapper.findListByStu(exchange);*/

        if("key1".equals(exchange.getExchangeType())){//选择层
            queryList  = exchangeMapper.findListByCh(exchange);
        }else if("key2".equals(exchange.getExchangeType())){//房间
            queryList  = exchangeMapper.findListByFjh(exchange);

        }else if("key3".equals(exchange.getExchangeType())){//学生
            queryList  = exchangeMapper.findListByStu(exchange);

        }
        System.out.println("=====:"+queryList);
        return RepeatPage.setRecords(queryList);
    }



    @Override
    public List<Map<String, String>> listByPid2(String pid) {
        List<Map<String, String>> list = exchangeMapper.listByPid2(pid);
        System.out.println("======================="+list);
      /*  LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        if (role.contains("fdy")) {//不是管理员，显示辅导员所在班级的学生
            List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
            String selectedSchools = sysUser.getSelectedSchools();
            if (oConvertUtils.isNotEmpty(selectedSchools)) {
                String[] fields = selectedSchools.trim().split(",");
                QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
                queryWrapperScl.in("sys_org_code", Arrays.asList(fields));
                List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);

                list.stream().forEach(item -> {
                    schoolList.stream().forEach(item2 -> {
                        if (String.valueOf(item.get("id")).equals(item2.getId())) {
                            list2.add(item);
                        }
                    });
                });
            }
            return list2;
        }*/
        return list;
    }


    @Override
    public Result<?>  exchangeBed(Exchange exchange) {

        if ("key1".equals(exchange.getExchangeType())) {//层
            return this.checkCh(exchange);
        } else if ("key2".equals(exchange.getExchangeType())) {//房间
            return this.checkFjh(exchange);
        } else if ("key3".equals(exchange.getExchangeType())) {//学生
            return this.checkStu(exchange);
        }
        return Result.OK("ok");
    }

    public Result<?>  checkCh(Exchange exchange) {
        try {
            List<Map<String, String>>  list1 =  exchangeMapper.getStudentByCh(Arrays.asList(exchange.getIdsOne().split(",")));
            List<Map<String, String>>  list2 =  exchangeMapper.getStudentByCh(Arrays.asList(exchange.getIdsTwo().split(",")));
            return exchangeByFj(list1,list2);
        }catch (Exception e){
            return Result.error("error");
        }
    }

    public Result<?>  checkFjh(Exchange exchange) {
        try {
            List<Map<String, String>>  list1 =  exchangeMapper.getStudentByFjh(Arrays.asList(exchange.getIdsOne().split(",")));
            List<Map<String, String>>  list2 =  exchangeMapper.getStudentByFjh(Arrays.asList(exchange.getIdsTwo().split(",")));
           return exchangeByFj(list1,list2);
        }catch (Exception e){
            return Result.error("error");
        }
    }

    public  Result<?>  exchangeByFj(List<Map<String, String>> list1,List<Map<String, String>> list2){
        List<LwgyBaseBed> bedList = new ArrayList<>();
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        LwgyBaseBed lwgyBaseBed;
        LwgyHotelHistory lwgyHotelHistory ;
        String tsIds = "";

        //请选择交换数据
        if(list1.size()>0 && list2.size()>0){
            ////选择双方的房间数一样
            if(list1.size() == list2.size()){
                for(int i=0;i<list1.size();i++){
                    Map map1  = (Map)list1.get(i);
                    Map map2  = (Map)list2.get(i);
                    //对调后住宿



                    Integer bedcount1 = Integer.parseInt(map1.get("bed_count").toString());//交换一的床位数量
                    Integer stucount1 = Integer.parseInt(map1.get("stu_count").toString());//交换一的学生数量
                    Integer bedcount2 = Integer.parseInt(map2.get("bed_count").toString());//交换二的床位数量
                    Integer stucount2 = Integer.parseInt(map2.get("stu_count").toString());//交换二的学生数量
                    if(stucount1>bedcount2 || stucount2>bedcount1){//比较每两个房间，学生数大于对方的床位数，不能交换
                        return Result.error("存在学生数大于待交换床位数情况");
                    }else{
                        tsIds += map1.get("ids") + ",";
                        String[] ids1 = map1.get("ids").toString().split(",");//交换1房间的床位号
                        String[] stu1 = map1.get("stus").toString().split(",");//交换1房间的学生
                        String[] ids2 = map2.get("ids").toString().split(",");//交换2房间的床位号
                        String[] stu2 = map2.get("stus").toString().split(",");//交换2房间的学生
                        //往交换1中安排交换2的学生
                        for(int j=0;j<ids1.length;j++){
                            for(int k=0;k<stu2.length;k++) {//学生数肯定是小于或者等于对方的房间数
                                lwgyBaseBed = new LwgyBaseBed();
                                lwgyBaseBed.setId(ids1[k]);
                                lwgyBaseBed.setStudentId(stu2[k]);
                                lwgyBaseBed.setUpdateTime(new Date());
                                bedList.add(lwgyBaseBed);
                            }
                        }
                        //往交换2中安排交换1的学生
                        for(int j=0;j<ids2.length;j++){
                            for(int k=0;k<stu1.length;k++) {//学生数肯定是小于或者等于对方的房间数
                                lwgyBaseBed = new LwgyBaseBed();
                                lwgyBaseBed.setId(ids2[k]);
                                lwgyBaseBed.setStudentId(stu1[k]);
                                lwgyBaseBed.setUpdateTime(new Date());
                                bedList.add(lwgyBaseBed);
                            }
                        }
                        //去除掉原来的学生

                        for(int k=0;k<stu1.length;k++) {//学生数肯定是小于或者等于对方的房间数
                            if(oConvertUtils.isNotEmpty(stu1[k])){
                                //加历史
                                lwgyHotelHistory = new LwgyHotelHistory();
                                lwgyHotelHistory.setBehavior("change_bed");
                                lwgyHotelHistory.setPersonId(stu1[k]);
                                lwgyHotelHistory.setBeforeBed(ids1[k]);
                                lwgyHotelHistory.setAfterBed(ids2[k]);
                                arrangementList.add(lwgyHotelHistory);
                            }

                        }

                        for(int k=0;k<stu2.length;k++) {//学生数肯定是小于或者等于对方的房间数
                            if(oConvertUtils.isNotEmpty(stu2[k])) {
                                //加历史
                                lwgyHotelHistory = new LwgyHotelHistory();
                                lwgyHotelHistory.setBehavior("change_bed");
                                lwgyHotelHistory.setPersonId(stu2[k]);
                                lwgyHotelHistory.setBeforeBed(ids2[k]);
                                lwgyHotelHistory.setAfterBed(ids1[k]);
                                arrangementList.add(lwgyHotelHistory);
                            }
                        }
                    }
                }
                if (tsIds.length() > 0 && bedList.size() > 0) {
                    lwgyHotelArrangementService.cleanBed(tsIds);//批量清空住宿
                    lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
                    lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
                }
            }else{
                return Result.error("双方的房间数不同，无法进行交换");
            }
        }else{
            return Result.error("请选择交换数据");
        }
        return Result.OK("交换成功");
    }



    public Result<?>  checkStu(Exchange exchange){
        List<Map<String, String>>  list1 =  exchangeMapper.getStudentByCwh(Arrays.asList(exchange.getIdsOne().split(",")));
        List<Map<String, String>>  list2 =  exchangeMapper.getStudentByCwh(Arrays.asList(exchange.getIdsTwo().split(",")));
        //请选择交换数据
        if(list1.size()>0 && list2.size()>0){
            ////选择双方的床位数一样
            if(list1.size() == list2.size()) {
                List<LwgyBaseBed> bedList = new ArrayList<>();
                List<LwgyHotelHistory> arrangementList = new ArrayList<>();
                LwgyHotelHistory lwgyHotelHistory ;
                String tsIds = "";

                for(int i=0;i<list1.size();i++){
                    Map map1  = (Map)list1.get(i);
                    Map map2  = (Map)list2.get(i);
                    //对调后住宿

                    String bed1 = (String) map1.get("ids");
                    String stu1 =  (String)map1.get("stus");
                    String bed2 = (String) map2.get("ids");
                    String stu2 = (String)map2.get("stus");

                    LwgyBaseBed lwgyBaseBed1 = new LwgyBaseBed();
                    LwgyBaseBed lwgyBaseBed2 = new LwgyBaseBed();
                    lwgyBaseBed1.setId(bed1);
                    lwgyBaseBed1.setStudentId(stu2);
                    lwgyBaseBed1.setUpdateTime(new Date());
                    bedList.add(lwgyBaseBed1);

                    lwgyBaseBed2.setId(bed2);
                    lwgyBaseBed2.setStudentId(stu1);
                    lwgyBaseBed2.setUpdateTime(new Date());
                    bedList.add(lwgyBaseBed2);
                    //将对调前的清空
                    tsIds+=bed1+","+bed2+',';
                    //该条数据加历史
                    LwgyHotelHistory lwgyHotelHistory1 = new LwgyHotelHistory();
                    lwgyHotelHistory1.setBehavior("change_bed");
                    lwgyHotelHistory1.setPersonId(stu1);
                    lwgyHotelHistory1.setBeforeBed(bed1);
                    lwgyHotelHistory1.setAfterBed(bed2);
                    arrangementList.add(lwgyHotelHistory1);
                    LwgyHotelHistory lwgyHotelHistory2 = new LwgyHotelHistory();
                    lwgyHotelHistory2.setBehavior("change_bed");
                    lwgyHotelHistory2.setPersonId(stu2);
                    lwgyHotelHistory2.setBeforeBed(bed2);
                    lwgyHotelHistory2.setAfterBed(bed1);
                    arrangementList.add(lwgyHotelHistory2);
                }
                if (tsIds.length() > 0 && bedList.size() > 0) {
                    lwgyHotelArrangementService.cleanBed(tsIds);//批量清空住宿
                    lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
                    lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
                }
            }else{
                return Result.error("请选择相同数量数据进行交换");
            }
        }else{
            return Result.error("请选择交换数据");
        }
        return Result.OK("交换成功");
    }

}
